﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web.Script.Serialization;

namespace MAF.Common
{
    public class UiHelper
    {
        /// <summary>
        /// 执行非查询方法(增，改，删)
        /// </summary>
        /// <param name="typeName"></param>
        /// <param name="method"></param>
        [Obsolete("此方法公用到MAF后，无法读取到程序集的信息，暂时作废")]
        public static string ExecuteNonQuery(string typeName, string method)
        {
            // 获取类型
            Type objType = GetObjectType(typeName);
            // 创建对象
            object objInstance = Activator.CreateInstance(objType);
            // 调用方法
            return objType.InvokeMember(method, BindingFlags.InvokeMethod, null, objInstance, null) as string;
        }

        /// <summary>
        /// 执行UI方法，必须是静态方法
        /// </summary>
        /// <param name="uiName">ui的名字，必须是“命名空间.类名.静态属性名”，例如My.Blog.WebUI.ArticleUI</param>
        /// <param name="uiMethod">静态方法，返回字符串</param>
        /// <returns></returns>
        [Obsolete("此方法公用到MAF后，无法读取到程序集的信息，暂时作废")]
        public static string ExecuteNonQueryUI(string uiName, string uiMethod)
        {
            var arry = uiName.Split(". ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (2 > arry.Length)
                throw new ArgumentException("ui的名字，必须是“命名空间.类名.静态属性名”，例如My.Blog.WebUI.ArticleUI");

            var len = arry.Length-1;
            var arry1 = new string[len];
            Array.Copy(arry, arry1, len);

            Type t = Type.GetType("ArticleUI", true, true);
            object obj = t.InvokeMember(arry[len], BindingFlags.InvokeMethod | BindingFlags.Static, null, null, null);
            return (string)(obj.GetType().InvokeMember(uiMethod, BindingFlags.InvokeMethod, null, obj, null));
        }

        /// <summary>
        /// 执行查询方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="typeName"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static string Query(string typeName, string method)
        {
            // 获取类型
            Type objType = GetObjectType(typeName);
            // 创建对象
            object objInstance = Activator.CreateInstance(objType);
            // 调用方法
            object t = objType.InvokeMember(method, BindingFlags.InvokeMethod, null, objInstance, null);
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Serialize(t);
        }

        /// <summary>
        /// 获取类型
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        private static Type GetObjectType(string typeName)
        {
            return Type.GetType(string.Format("Web.UI.{0}UI", typeName), true, true);
        }
    }
}